import {View} from "@tarojs/components";
import {useEffect, useMemo, useRef, useState} from "react";
import Utils from "@/utils/common";
import DynamicForm, {FormConfig} from "@/components/DynamicForm";
import {addressDeleteApi, addressSaveApi, addressUpdateApi} from "@/common/apis/home_datasource";
import {AddressModel} from "@/common/apis/model";
import {Button} from "@antmjs/vantui";
import Taro from "@tarojs/taro";
import LocalData from "@/common/local_data";

definePageConfig({
  navigationBarTitleText: '新增地址'
})

export default function AddAddress() {
  // 表单配置
  const addressFormConfigs: FormConfig[] = [
    {
      type: 'input',
      name: 'recipient', // Logical name for recipient name
      label: '收件人',       // Label text (without *)
      placeholder: '请填写收件人',
      required: true,        // Has asterisk
      rules: [{required: true, message: '请输入收件人姓名'}]
    },
    {
      type: 'input',
      name: 'phone', // Logical name for contact phone
      label: '联系电话',     // Label text (without *)
      placeholder: '请填写联系电话',
      required: true,        // Has asterisk
      inputType: LocalData.phoneInputType,
      maxlength: 11,
      rules: [
        {rule: /^\d{11}$/, message: '请输入有效的手机号码'},
      ]
    },
    {
      // Although it's address, the UI shows a single-line input field style
      type: 'input',
      name: 'address', // Logical name for the detailed address
      label: '详细地址',       // Label text (without *)
      placeholder: '请填写详细地址',
      required: true,        // Has asterisk
      rules: [{required: true, message: '请输入详细地址'}]
    },
    {
      type: 'switch',        // Matches the visual toggle switch
      name: 'isDefault',     // Logical boolean-like name
      label: '设为默认',
      required: false,       // No asterisk
      rules: []
      // No placeholder for switches
    }
  ];

  const initValues = useRef<AddressModel>()
  const [showContent, setShowContent] = useState(false)
  const eventChannel = useRef<Taro.EventChannel | null>();
  useEffect(() => {
    const i = Utils.getI()
    const params =  Utils.getParamsByRouter(i)
    eventChannel.current = Utils.getChannel(i)
    if(params&&params.data){
      initValues.current = Utils.getObjectWithUrl<AddressModel>(params.data)
      Utils.setTitle('修改地址')
    }
    setShowContent(true)
  }, []);


  // 提交回调
  const handleSubmit = (values) => {
    console.log('Form values:', values);

    const formData = {
      ...values,
      isDefault: values.isDefault ? 1 : 0
    };
    const api = initValues.current ? addressUpdateApi({
      ...formData,
      id: initValues.current.id
    }) : addressSaveApi(formData);
    api.then((res) => {
      if (res) {
        Utils.showOkToast('保存成功')
        if (eventChannel.current) {
          Utils.emit(eventChannel.current, 'addressAdded', true)
          Utils.navigateBack({
            delta: 1 // Go back one page
          })
        }
      }
    })

    // 处理表单提交逻辑
  };

  // 错误回调
  const handleError = (errors) => {
    console.error('Form errors:', errors);
  };

  const data = useMemo(() => {
    if (!initValues.current) {
      return {}
    }
    const isDefault = initValues.current.isDefault === 1;
    return {
      ...initValues.current,
      isDefault: isDefault
    }
  }, [showContent]);

  return (
    <View className='form-page'>
      {
        (showContent) ? <DynamicForm
          formConfigs={addressFormConfigs}
          initialValues={data}
          onSubmit={handleSubmit}
          onError={handleError}
          submitText='保存地址'
          otherOperate={() => {
            return initValues.current ?
              <Button type='danger' plain hairline style={{margin: '24px 0 24px 24px'}} onClick={() => {
                if (initValues.current.id) {
                  Utils.modal('删除地址', '确定要删除该地址吗？', true, (ok) => {
                    if(ok){
                      addressDeleteApi(initValues.current.id).then((res) => {
                        if (res) {
                          Utils.showOkToast('删除成功')
                          if (eventChannel.current) {
                            Utils.emit(eventChannel.current, 'addressAdded', true)
                            Utils.navigateBack({
                              delta: 1 // Go back one page
                            })
                          }
                        }
                      })
                    }
                  })
                }
              }}
              >删除地址</Button> : null
          }}
        /> : null
      }
    </View>
  );
}


